<?php

namespace Beerus\Modules\DecoCalculator\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\DecoCalculator\DecoCalculatorDesign as mDecoCalculatorDesign;
use Illuminate\Support\MessageBag;
use Doraemon\service\DecorationCalculator\GetCountPrice;

class DesignController
{
    // 列表
    public function index(Request $request,Content $content) {
        $pageSize = $request->input("per_page", 10);
        $page = $request->input("page", 1);

        $list = mDecoCalculatorDesign::listByCondition([
            'data_status' => mDecoCalculatorDesign::STATUS_NORMAL,
            'LIMIT' => [($page - 1) * $pageSize, $pageSize ],
        ]);
        $total = mDecoCalculatorDesign::countByCondition([
            'data_status' => mDecoCalculatorDesign::STATUS_NORMAL,
        ]);
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableFilter();
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->column("id", 'ID');
                $grid->column("deco_specs", "装修规格")->display(function () {
                    return mDecoCalculatorDesign::SPECS_MAP[$this->deco_specs];
                });
                $grid->column("unit_price", "单价")->display(function () {
                    return $this->unit_price/100;
                });
                $grid->column("sort", "排序");
                $grid->column("edit_time", '修改时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->edit_time);
                });
                $grid->column("admin_id", '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '-';
                    } else {
                        return Admin::user()->find($this->admin_id)->name;
                    }
                });

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                });
            });

        $tab = new Tab();
        $tab->add('设计费配置列表', $gridList->render());
        $content->row($tab);
        return $content
            ->header('设计费配置列表')
            ->description(' ')
            ->breadcrumb(['text' => '设计费配置列表']);
    }

    // 编辑
    public function edit(Content $content, $id = 0)
    {
        if($id == 0) {
            return $content
                ->header('设计费配置 - 新增')
                ->breadcrumb([
                    'text' => '设计费配置列表',
                    'url' => '/DecoCalculator/design/',
                ])
                ->body(self::editAction($id));
        } else {
            return $content
                ->header('设计费配置 - 编辑')
                ->breadcrumb([
                    'text' => '设计费配置列表',
                    'url' => '/DecoCalculator/design/',
                ])
                ->body(self::editAction($id));
        }
    }

    public function editAction($id)
    {
        if($id == 0) {
            $data = [];
            $form = new Form($data);
        } else {
            $data = mDecoCalculatorDesign::getByCondition(['id' => $id]);
            $data['unit_price'] = $data['unit_price']/100;
            $form = new Form($data);
            $form->hidden('id');
        }

        $form->text('unit_price', '单价')->required()->pattern('^([1-9][0-9]*){1,10}$')->setWidth(4, 2)->help("请填写正整数");
        $form->select('deco_specs', '装修规格')->options(mDecoCalculatorDesign::SPECS_MAP)->required()->setWidth(4, 2);
        $form->text('sort', '排序')->required()->pattern('^([1-9][0-9]*){1,10}$')->setWidth(4, 2)->help("请填写正整数");
        $form->action('/admin/DecoCalculator/design/save');
        return $form->render();
    }

    // 提交
    public function editSubmit(Request $request)
    {
        try {
            $params = $request->all();

            $data = [
                'unit_price' => $params['unit_price'] * 100,
                'deco_specs' => $params['deco_specs'],
                'sort' => $params['sort'],
                'admin_id' => Admin::user()->id,
            ];

            if ($params['id']) {
                $data['edit_time'] = time();
                mDecoCalculatorDesign::updateInfo($data, [
                    'id' => $params['id']
                ]);

                $title = '修改成功';
                //清除计算器的数据缓存
                GetCountPrice::delCountPriceData();
            } else {
                // 验证规格唯一
                $specs = mDecoCalculatorDesign::getByCondition(['deco_specs' => $params['deco_specs']]);
                if ($specs) {
                    throw new \Exception("该装修规格单价已配置，请勿重复配置");
                }

                $data['add_time'] = time();
                mDecoCalculatorDesign::addInfo($data);

                $title = '添加成功';
                //清除计算器的数据缓存
                GetCountPrice::delCountPriceData();
            }

            $success = new MessageBag([
                'title' => $title
            ]);
            return redirect('/admin/DecoCalculator/design')->with(compact('success'));

        }  catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage(),
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function delete($id)
    {
        $update_data = [
            'data_status' => mDecoCalculatorDesign::STATUS_DELETE,
            'admin_id' => Admin::user()->id,
        ];
        if (!mDecoCalculatorDesign::updateInfo($update_data, ['id' => $id])) {
            return response()->json([
                'status' => false,
                'message' => "删除失败",
            ]);
        }
        //清除计算器的数据缓存
        GetCountPrice::delCountPriceData();
        return response()->json([
            'status' => true,
            'message' => "删除成功",
        ]);
    }
}
